package domain

import (
	"context"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"grpc-common/ucenter/types/login"
	"listenboos-common/db"
	"listenboos-common/tools"
	"time"
	"ucenter/dao"
	"ucenter/model"
	"ucenter/repo"
)

type UserInfoDomain struct {
	userRepo repo.UserInfoRepo
}

func (u *UserInfoDomain) FindByOpenId(ctx context.Context, openId string) (user *model.UserInfo, err error) {
	userInfo, err := u.userRepo.FindByOpenId(ctx, openId)
	if err != nil {
		logx.Error(err)
		return nil, errors.New("数据库异常")
	}
	return userInfo, err
}

func (u *UserInfoDomain) Save(ctx context.Context, openId string) (user *model.UserInfo, err error) {
	userInfo := model.NewUserInfo()
	userInfo.WxOpenId = openId
	userInfo.AvatarUrl = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2Fe711d64a-9299-482e-9dac-e917ebe0db10%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1696912453&t=339c44cb27ea5321aa3eb7b07fe7bb2e"
	number := time.Now().Unix()
	userInfo.Nickname = fmt.Sprintf("听友%d", number)
	now := time.Now().UnixMilli()
	timeString := tools.ToTimeString(now)
	userInfo.CreateTime = timeString
	userInfo.UpdateTime = timeString
	err = u.userRepo.Save(ctx, userInfo)
	if err != nil {
		logx.Error(err)
		return nil, errors.New("数据库异常")
	}

	return userInfo, nil
}

func (u *UserInfoDomain) FindById(ctx context.Context, id int64) (user *model.UserInfo, err error) {
	user, err = u.userRepo.FindById(ctx, id)
	if err != nil {
		return nil, err
	}
	return user, nil
}

func (u *UserInfoDomain) UpdateUser(in *login.UpdateUserReq) error {
	err := u.userRepo.UpdateUser(context.Background(), in.Id, in.AvatarUrl, in.Nickname)
	if err != nil {
		logx.Error(err)
		return errors.New("数据库异常")
	}
	return nil
}

func NewUserInfoDomain(db *db.ListenDB) *UserInfoDomain {
	return &UserInfoDomain{
		userRepo: dao.NewUserInfoDao(db),
	}
}
